package com.beijing.cyou.config;

import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;

@Slf4j
@Configuration 
public class RedisConnection implements InitializingBean {

	private static final Integer poolDownSize = 0 ;
	
	private static final Integer poolUpSize = 15 ;
	
	public Map<Integer, JedisPool> jedisPoolMap = new HashMap<Integer, JedisPool>();
	
	@Autowired
	private RedisPool redisPool ;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		for(int i = poolDownSize ; i <= poolUpSize ; i++) {
			JedisPool jedisPool = new JedisPool(redisPool.getPoolConfig(),redisPool.getHost(), 
						redisPool.getPort(),redisPool.getTimeout(),redisPool.getPassword(),i);
			jedisPoolMap.put(i, jedisPool) ;
		}
		log.info("\n @@ RedisConnection - InitializingBean Complete ! ## \n");
	}
	
	public JedisPool chooseJedisPool(Integer dbnum) {
		if ( dbnum == null || dbnum > poolUpSize || dbnum < poolDownSize) {
			log.info("%%% redis-pool 选择有误 ！ @@@");
			return null ;
		}else if (dbnum == poolDownSize) {
			return jedisPoolMap.get(dbnum) ;
		}else {
			log.info("## Connection : " + redisPool.getHost() + "->redis[" +dbnum + "]>>");
			return jedisPoolMap.get(dbnum) ;
		}
	}

	public RedisPool getRedisPool() {
		return redisPool;
	}
	
}
